package com.supcalls.atomic;

import java.util.concurrent.atomic.AtomicStampedReference;

public class ABASolutionDemo {

    public static void main(String[] args) {
        // 初始化值为 "A"，版本号为 0
        String initialValue = "A";
        int initialStamp = 0;
        AtomicStampedReference<String> atomicReference = new AtomicStampedReference<>(initialValue, initialStamp);

        // 创建多个线程模拟 ABA 问题
        // Thread-1 修改值为 "B"
        Thread t1 = new Thread(() -> {
            int stamp = atomicReference.getStamp();
            System.out.println("Thread-1 initial stamp: " + stamp);
            atomicReference.set("B", stamp + 1);
            System.out.println("Thread-1 updated value to: " + atomicReference.getReference());
        });

        // Thread-2 恢复值为 "A"
        Thread t2 = new Thread(() -> {
            int stamp = atomicReference.getStamp();
            System.out.println("Thread-2 initial stamp: " + stamp);
            atomicReference.set("A", stamp + 1);
            System.out.println("Thread-2 updated value back to: " + atomicReference.getReference());
        });

        // Thread-3 尝试使用 CAS 更新值
        Thread t3 = new Thread(() -> {
            int stamp = atomicReference.getStamp();
            System.out.println("Thread-3 CAS attempt with stamp: " + stamp);
            boolean success = atomicReference.compareAndSet("A", "C", stamp, stamp + 1);
            System.out.println("Thread-3 CAS result: " + success + ", Current value: " + atomicReference.getReference());
        });

        // 启动线程
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 启动 Thread-3
        t3.start();
        try {
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 最终的值
        System.out.println("Final value: " + atomicReference.getReference() + ", Final stamp: " + atomicReference.getStamp());
    }
}
